package com.fleafinder;

import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.fleafinder.entity.Category;
import com.fleafinder.entity.Market;
import com.fleafinder.entity.MarketType;

public class MarketListFragment extends ListFragment {

	private ListViewMarketListAdapter listViewMarketListAdapter = null;
	private List<Market> marketList = null;
	private String categoryName = "";

	public List<Market> getMarketList() {
		marketList = GetMarket();
		return marketList;
	}

	public ListViewMarketListAdapter getListViewMarketListAdapter() {
		return listViewMarketListAdapter;
	}

	public void setListViewMarketListAdapter() {
		listViewMarketListAdapter = new ListViewMarketListAdapter(
				this.getActivity(), this.getMarketList());
		listViewMarketListAdapter.notifyDataSetChanged();

	}

	// @Override
	// public void onActivityCreated(Bundle savedInstanceState) {
	// // TODO Auto-generated method stub
	// super.onActivityCreated(savedInstanceState);
	//
	// /*ArrayAdapter<Market> adapter*/listViewMarketListAdapter = new
	// ListViewMarketListAdapter(
	// this.getActivity(), this.getMarketList());
	// setListAdapter(listViewMarketListAdapter);
	// }

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.market_list_fragment, container,
				false);
		/* ArrayAdapter<Market> adapter */listViewMarketListAdapter = new ListViewMarketListAdapter(
				this.getActivity(), this.getMarketList());
		// System.out.println("The size of Market List: " + marketList.size());

		if (listViewMarketListAdapter.getCount() == 0) {
			Toast t = Toast.makeText(view.getContext(),
					CommonConstants.MARKETLIST_EMPTY_ALERT, Toast.LENGTH_SHORT);
			t.setGravity(Gravity.CENTER_HORIZONTAL, 5, 5);
			t.show();
		}

		setListAdapter(listViewMarketListAdapter);

		TextView textView = (TextView) view.findViewById(R.id.market_list);
		textView.setText(categoryName);
		return view;
	}

	public List<Market> GetMarket() {

		DataCenter dataCenter = DataCenter.getInstance();
		int currentmarketListMode = dataCenter.getCurrentMarketListMode();
		int selectedMarketTypeList = dataCenter.getSelectedMarketTypeId();

		// TODO [Fleafinder] Is it possible to use "if (){...} else if (){...}
		// in the following checkings on variable currentmarketListMode
		// it helps to reduce number of comparison that the program has to run
		// --> reduce CPU usage.

		List<Market> marketList = new ArrayList<Market>(20);

		if (currentmarketListMode == CommonConstants.MARKETTYPE_AND_CATEGORY) {
			int selectedMarketCategory = dataCenter.getSelectedMaketCategory();
			MarketType selectedMarketType = getMarketType(
					dataCenter.getMarketTypeList(), selectedMarketTypeList);
			List<Market> marketListByType = dataCenter.getDataOrganized().get(
					selectedMarketType);

			for (Market m : marketListByType) {
				for (Category cat : m.getCategories()) {
					if (cat.getId() == selectedMarketCategory) {
						marketList.add(m);
						categoryName = cat.getName();
						break;
					}
				}
			}
			Log.i("MARLIST", "LOAD DATA" + currentmarketListMode);
			return marketList;
		}
		if (currentmarketListMode == CommonConstants.MARKETTYPE_AND_VISALLE) {
			MarketType selectedMarketType = getMarketType(
					dataCenter.getMarketTypeList(), selectedMarketTypeList);
			Log.d("10", "MARKETTYPE_AND_VISALLE");
			marketList = dataCenter.getDataOrganized().get(selectedMarketType);
			Log.i("MARLIST", "LOAD DATA" + currentmarketListMode);
			categoryName = getResources().getString(R.string.view_all);
			return marketList;
		}

		if (currentmarketListMode == CommonConstants.ALL_MARKETTYPE) {
			marketList = dataCenter.getMarketList();
			Log.d("10", "ALL_MARKETTYPE");
			Log.i("MARLIST", "LOAD DATA" + currentmarketListMode);
			categoryName = getResources().getString(R.string.view_all);
			return marketList;
		}

		if (currentmarketListMode == CommonConstants.TOP_MARKEDER) {
			marketList = dataCenter.getBusinessMarketList();
			Log.i("MARLIST", "LOAD DATA" + currentmarketListMode);
			categoryName = getResources().getString(R.string.top_market);
			return marketList;
		}

		return marketList;
	}

	private MarketType getMarketType(List<MarketType> marketTypes, int id) {
		for (MarketType mt : marketTypes) {
			if (mt.getMarketId() == id) {
				return mt;
			}
		}
		return null;
	}

	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		DataCenter dc = DataCenter.getInstance();
		dc.setRootFragmentOfTab(false);
		
		MarketDetailsFragment detailsFragment = null;
		Market m = dc.readMarkedInfo(ListViewMarketListAdapter.list.get(
				position).getId());
		String tag = "";
		if (dc.getCurrentMarketListMode() == CommonConstants.TOP_MARKEDER) {
			detailsFragment = dc.getMarketDetailsFragmentForTopMarkeder(m);
			tag = CommonConstants.TOP_FRAGMENT;
		} else {
			detailsFragment = dc.getMarketDetailsFragment(m);
			tag = CommonConstants.HOME_FRAGMENT;
		}

		if (detailsFragment.isFullyInitialized()) {
			detailsFragment.updateViewWithMarket(m);
		}

		FragmentActivity activity = (FragmentActivity) v.getContext();
		FragmentManager fm = activity.getSupportFragmentManager();
		FragmentTransaction transaction = fm.beginTransaction();

		transaction.replace(R.id.fragment_placeholder, detailsFragment, tag);
		transaction.addToBackStack(tag);
		transaction.commit();

		// while(!detailsFragment.isFullyInitialized()){
		// try {
		// Thread.sleep(1000);
		// } catch (InterruptedException e) {
		// e.printStackTrace();
		// }
		// }
		// detailsFragment.updateViewWithMarket(m);
	}
}
